const multer = require("multer");
const MAO = require("multer-aliyun-oss");
const OSS = require("ali-oss");
const { BadRequest } = require("http-errors");

const config = {
  region: process.env.OSS_REGION,
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  bucket: process.env.OSS_BUCKET,
};

const client = new OSS(config);

// multer配置信息
const upload = multer({
  storage: MAO({
    config: config,
    destination: "uploads", //上传文件的目录
  }),
  limits: {
    fileSize: 1024 * 1024 * 20, //限制文件大小:20M
  },
  fileFilter: function (req, file, cb) {
    const fileType = file.mimetype.split("/")[0];
    const isImage = fileType === "image";
    if (!isImage) {
      return cb(new BadRequest("只允许上传图片!"));
    }
    cb(null, true);
  },
});

// 单文件上传,指定表单字段为file
const singleFileUpload = upload.single("file"); //单文件上传
const singleFileUploads = upload.any("files"); //多文件上传
module.exports = {
  config,
  singleFileUpload,
  singleFileUploads,
  client,
};
